#!/usr/bin/env bash
# 实例文件： mkalbum
# mkalbum - 制作HTML相册
# 版本号0.2

#ERROUT
ERROUT()
{
    printf "%b" "$@"
} >&2

#USAGE
USAGE()
{
    ERROUT "usage: %s <newdir>\n" ${0##*/}
}

#EMIT(thisph, startph, prevph, nextph, lastph)

EMIT()
{
    THISPH="../$1"
    STARTPH="${2%.*}.html"
    PREVPH="${3%.*}.html"
    NEXTPH="${4%.*}.html"
    LASTPH="${5%.*}.html"

    if [ -z "$3" ]
    then
        PREVLINE='<TD>Prev</TD>'
    else
        PREVLINE='<TD><A HREF="'$PREVPH'">Prev</A></TD>'
    fi
    if [ -z "$4" ]
    then
        NEXTLINE='<TD>Next</TD>'
    else
        NEXTLINE='<TD><A HREF="'$NEXTPH'">Next</A></TD>'
    fi
cat << EOF
<HTML>
<HEAD><TITLE>$THISPH</TITLE></HEAD>
<BODY>
  <H2>$THISPH</H2>
<TABLE WIDTH="25%">
  <TR>
    <TD><A HREF="$STARTPH">First</A></TD>
    $PREVLINE
    $NEXTLINE
    <TD><A HREF="$LASTPH">Last</A></TD>
  </TR>
</TABLE>
  <IMG SRC="$THISPH" alt="$THISPH"
   BORDER="1" VSPACE="4" HSPACE="4"
   WIDTH="800" HEIGHT="600" />
</BODY>
</HTML>
EOF
}
if (( $# != 1 ))
then
    USAGE
    exit -1
fi

ALBUM="$1"

if [ -d "${ALBUM}" ]
then
    ERROUT "Directory [%s] already exists.\n" ${ALBUM}
    USAGE
    exit -2
else
    mkdir "$ALBUM"
fi

cd "$ALBUM"

PREV=""
FIRST=""
LAST="last"

while read PHOTO
do
# 开始制作相册
    if [ -z "${CURRENT}" ]
    then
        CURRENT="$PHOTO"
        FIRST="$PHOTO"
        continue
    fi

    PHILE=${CURRENT##*/}
    EMIT "$CURRENT" "$FIRST" "$PREV" "$PHOTO" "$LAST" > "${PHILE%.*}.html" 
    PREV="$CURRENT"
    CURRENT="$PHOTO"
done

PHILE=${CURRENT##*/}
EMIT "$CURRENT" "$FIRST" "$PREV" "" "$LAST" > "${PHILE%.*}.html"

ln -s "${PHILE%.*}.html" ./last.html
ln -s "${FIRST%.*}.html" ./index.html

